package petClinic;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

public class PersonHibernateDAO implements PersonDAO{

	private SessionFactory factory;
	
	public PersonHibernateDAO(){
		factory = HibernateUtil.getSessionFactory();
	}

	@Override
	public void insertOrUpdate(Person p) {
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		session.saveOrUpdate(p);
		tx.commit();
		session.close();	
	}

	@Override
	public void delete(int id) {
		Session session = factory.openSession();
		Person p = (Person) session.get(Person.class, id);
		Transaction tx = session.beginTransaction();
		session.delete(p);
		tx.commit();
		session.close();	
	}
	
	public void delete(Person p) {
		Session session = factory.openSession();
		Transaction tx = session.beginTransaction();
		session.delete(p);
		tx.commit();
		session.close();	
	}

	
	@Override
	public Person findById(int id) {
		Session session = factory.openSession();
		Person p = (Person) session.get(Person.class, id);
		session.close();
		return p;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void findAll() {
		Session session = factory.openSession();
		Query q = session.createQuery("from Person");
		List<Person> persons = q.list();
		for (Person person : persons) {
			System.out.println(person);
		}
		session.close();	
		
	}
}